package com.iot08.admin.service;

import com.iot08.admin.service.page.PageVO;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.Account;
import com.iot08.common.response.Response;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @version 1.0
 * @Description: app用户
 * @time: 2020/9/1 11:48
 * @author: Rock
 */
@Slf4j
@Service
public class AccountService extends BaseService<Account> {

    @Resource
    private OperationService operationService;
    //@Resource
    //private NotifyService notifyService;


    public long countWithPhone(String phone) {
        Query query = new Query(Criteria.where("phone").is(phone));
        return this.count(query);
    }
    public long countWithEmail(String email) {
        Query query = new Query(Criteria.where("email").is(email));
        return this.count(query);
    }
    /**
     * 列表数据
     *
     * @param [page, imei, state]
     * @time: 2020/9/1 17:05
     * @author: Rock
     * @version 1.0
     */
    public Page<Account> list(PageVO page, String imei, Integer state, Integer sortState) {
        PageableImpl pageable = new PageableImpl();
        Sort sort = Sort.by(Sort.Order.desc("registerDate"));
        if(sortState != null){
            if (sortState == 0) {
                sort = Sort.by(Sort.Order.desc("registerDate"));
            } else if (sortState == 1) {
                sort = Sort.by(Sort.Order.asc("registerDate"));
            } else if (sortState == 2) {
                sort = Sort.by(Sort.Order.desc("loginDate"));
            } else if (sortState == 3) {
                sort = Sort.by(Sort.Order.asc("loginDate"));
            } else if (sortState == 4) {
                sort = Sort.by(Sort.Order.desc("recentlyTime"));
            } else if (sortState == 5) {
                sort = Sort.by(Sort.Order.asc("recentlyTime"));
            }
        }
        page.setSort(sort);
        pageable.setPage(page);

        Criteria criteria = new Criteria();
        if (StringUtils.isNotEmpty(page.getSearchValue())) {
            criteria.and("phone").regex(".*?" + page.getSearchValue() + ".*?", "i");
        }
        if (StringUtils.isNotEmpty(imei)) {
            //TODO 长见识
            criteria.and("d." + imei).exists(true);
        }
        if (state != null) {
            if (state == 0) {
                criteria.and("forbidden_status").ne(1);
            } else {
                criteria.and("forbidden_status").is(state);
            }
        }

        Query query = new Query().addCriteria(criteria);
        long count = this.count(query);
        page.setTotalResult((int) count);
        List<Account> list = this.find(query.with(pageable));
        Page<Account> result = new PageImpl<Account>(list, pageable, count);
        return result;
    }

    /**
     * @param [id, pwd]
     * @time: 2020/9/2 10:48
     * @author: Rock
     * @version 1.0
     */
    public void updatePwd(String id, String pwd, SysUser user, String ip) {
        Query query = new Query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("P", pwd);
        mongoTemplate.updateFirst(query, update, Account.class);
        Account account = mongoTemplate.findOne(query, Account.class);
        String name = getName(account);
        //发送通知
        //notifyService.updateAccountToken(id, "refreshPWD");
        //notifyService.sendPushToAccount(id, "DIY", "您的账号密码给重置了，请重新登录");

        //添加操作日志
        operationService.add(user, ip, null, "用户管理", null,
                "修改密码", String.format("%s 修改账号：%s的登录密码", user.getNickname(), name),
                null, null, null);

    }

    /**
     * @param [id, forbiddenStatus]
     * @time: 2020/9/2 10:19
     * @author: Rock
     * @version 1.0
     */
    public void updateForbiddenStatus(String id, String forbiddenStatus, SysUser user, String ip) {
        Query query = new Query(Criteria.where("id").is(id));
        Update update = new Update();

        Account account = this.findOne(query);
        String name = getName(account);
        if ("1".equals(forbiddenStatus)) {
            update.set("forbidden_status", forbiddenStatus);
            //发送通知
            //notifyService.updateAccountToken(id, "forbidden");
            //notifyService.sendPushToAccount(id, "disableAccount", "");

            //添加操作记录
            operationService.add(user, ip, null, "用户管理", null,
                    "禁用", String.format("%s 禁用账号：%s", user.getNickname(), name),
                    null, null, null);
        } else {
            update.unset("forbidden_status");
            operationService.add(user, ip, null, "用户管理", null,
                    "启用", String.format("%s 启用账号：%s", user.getNickname(), name),
                    null, null, null);
        }

        this.update(query, update);
    }

    /**
     * @param [account]
     * @time: 2020/9/2 17:51
     * @author: Rock
     * @version 1.0
     */
    private String getName(Account account) {
        String name = "";
        if (account != null) {
            if (account.getCountryCode() != null) {
                name = String.format("(+%s)-%s", account.getCountryCode(), account.getPhone());
            } else if (StringUtils.isNotEmpty(account.getWxName())) {
                name = account.getWxName();
            } else if (StringUtils.isNotEmpty(account.getQqid())) {
                name = account.getQqid();
            } else if (StringUtils.isNotEmpty(account.getImei())) {
                name = account.getImei();
            }
        }
        return name;
    }

    /**
     * @param [id, user]
     * @time: 2020/9/2 18:09
     * @author: Rock
     * @version 1.0
     */
    public Response<Object> del(String id, SysUser user, String ip) {
        //权限检查
        if (user.getType() == 1) {
            log.error("({}){} 权限不足 IP:{}",user.getId(), user.getAccount(), ip);
            return Response.failedResponse("权限不足");
        }

        Query query = new Query(Criteria.where("id").is(id));
        Account account = this.findOne(query);
        if (account.getDeviceMap() instanceof LinkedHashMap
                && ((LinkedHashMap) account.getDeviceMap()).keySet().size() > 0) {
            return Response.failedResponse("需先解除关联的设备");
        }
        String name = getName(account);
        this.delById(id);
        //操作日志
        operationService.add(user, ip, null, "用户管理", null,
                "删除", String.format("%s 删除账号：%s", user.getNickname(), name),
                null, null, null);
        return Response.successResponse();
//        return Response.failedResponse();
    }

    public void add(Account account) {
        account.setRegisterDate(new Date());
        account.setLoginDate(new Date());
        //deleteNotificationtime
        double time = DateUtil.nowTimestampToDouble();
        account.setTimestamp(time);
        account.setDeleteNotificationtime(time);

        this.save(account);
    }
}
